package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.pojo.Employee;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;


    @Override
    public Result<String> edit(EmployeeDTO employeeDTO) {
        //1.参数校验
        if (ObjectUtils.isEmpty(employeeDTO)) {
            return Result.error("参数错误");
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
        return Result.success();
    }

    @Override
    public Result<Employee> getById(Long id) {
        //1.校验参数
        if (ObjectUtils.isEmpty(id)) {
            return Result.error("参数错误");
        }
        Employee employee = employeeMapper.getById(id);
        if (Objects.isNull(employee)) {
            return Result.error("员工不存在");
        }else {
            //脱敏
            employee.setPassword("");
        }
        // 三.封装数据
        return Result.success(employee);
    }

    @Override
    public Result<String> startOrStop(Integer status, Long id) {
        //1.校验参数
        if (status == null || status < 0 || status > 1) {
            return Result.error("参数错误");
        }
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.updateStatus(employee);
        return Result.success();
    }

    @Override
    public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO) {
        //1.校验参数
        //判断参数是否为空
        int page = employeePageQueryDTO.getPage();
        int pageSize = employeePageQueryDTO.getPageSize();
        if (page <= 0 || pageSize <= 0) {
            return Result.error("分页参数非法");
        }
        // 二.处理业务
        // 1.分页设置
        PageHelper.startPage(page, pageSize);
        // 2.条件查询
        Page<Employee> pageInfo = employeeMapper.selectPageByName(employeePageQueryDTO.getName());
        //封装数据
        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setRecords(pageInfo.getResult());
        return Result.success(pageResult);
    }

    @Override
    public Result<String> addEmployee(EmployeeDTO employeeDTO) {
        //1.校验参数
        //判断employeeDTO对象是否为空
        if (Objects.isNull(employeeDTO)) {
            return Result.error("参数错误");
        }
        //业务处理
        Employee employee = new Employee();
        //只有数据类型跟属性名都相同的情况下,才能拷贝成功
        BeanUtils.copyProperties(employeeDTO, employee);
        //1.补全实体属性
//        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        employee.setStatus(StatusConstant.ENABLE);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //TODO 现在给个假的,后面再优化
//        employee.setCreateUser(10L);
//        employee.setUpdateUser(10L);
        // 2.保存到数据库
        employeeMapper.insert(employee);
        //三、封装数据
        return Result.success();
    }

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();//

        //1、根据用户名查询数据库中的数据  select * from employee where username = #{username}
        Employee employee = employeeMapper.getByUsername(username); //

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }


}
